<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>C++20 Coroutines Support</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../core.html" title="Core Concepts and Functionality">
<link rel="prev" href="spawn.html" title="Stackful Coroutines">
<link rel="next" href="coro.html" title="Resumable C++ 20 Coroutines">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="spawn.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../core.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="coro.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.overview.core.cpp20_coroutines"></a><a class="link" href="cpp20_coroutines.html" title="C++20 Coroutines Support">C++20 Coroutines
        Support</a>
</h4></div></div></div>
<p>
          Support for C++20 Coroutines is provided via the <a class="link" href="../../reference/awaitable.html" title="awaitable"><code class="computeroutput">awaitable</code></a>
          class template, the <a class="link" href="../../reference/use_awaitable_t.html" title="use_awaitable_t"><code class="computeroutput">use_awaitable</code></a>
          completion token, and the <a class="link" href="../../reference/co_spawn.html" title="co_spawn"><code class="computeroutput">co_spawn()</code></a>
          function. These facilities allow programs to implement asynchronous logic
          in a synchronous manner, in conjunction with the <code class="computeroutput">co_await</code>
          keyword, as shown in the following example:
        </p>
<pre class="programlisting">boost::asio::co_spawn(executor, echo(std::move(socket)), boost::asio::detached);

// ...

boost::asio::awaitable&lt;void&gt; echo(tcp::socket socket)
{
  try
  {
    char data[1024];
    for (;;)
    {
      std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data), boost::asio::use_awaitable);
      co_await async_write(socket, boost::asio::buffer(data, n), boost::asio::use_awaitable);
    }
  }
  catch (std::exception&amp; e)
  {
    std::printf("echo Exception: %s\n", e.what());
  }
}
</pre>
<p>
          The first argument to <code class="computeroutput">co_spawn()</code> is an <a class="link" href="../../reference/Executor1.html" title="Executor requirements">executor</a>
          that determines the context in which the coroutine is permitted to execute.
          For example, a server's per-client object may consist of multiple coroutines;
          they should all run on the same <code class="computeroutput">strand</code> so that no explicit
          synchronisation is required.
        </p>
<p>
          The second argument is an <a class="link" href="../../reference/awaitable.html" title="awaitable"><code class="computeroutput">awaitable&lt;R&gt;</code></a>,
          that is the result of the coroutine's entry point function, and in the
          above example is the result of the call to <code class="computeroutput">echo</code>. (Alternatively,
          this argument can be a function object that returns the <a class="link" href="../../reference/awaitable.html" title="awaitable"><code class="computeroutput">awaitable&lt;R&gt;</code></a>.)
          The template parameter <code class="computeroutput">R</code> is the type of return value produced
          by the coroutine. In the above example, the coroutine returns <code class="computeroutput">void</code>.
        </p>
<p>
          The third argument is a completion token, and this is used by <code class="computeroutput">co_spawn()</code>
          to produce a completion handler with signature <code class="computeroutput">void(std::exception_ptr,
          R)</code>. This completion handler is invoked with the result of the coroutine
          once it has finished. In the above example we pass a completion token type,
          <a class="link" href="../../reference/detached.html" title="detached"><code class="computeroutput">boost::asio::detached</code></a>,
          which is used to explicitly ignore the result of an asynchronous operation.
        </p>
<p>
          In this example the body of the coroutine is implemented in the <code class="computeroutput">echo</code>
          function. When the <code class="computeroutput">use_awaitable</code> completion token is passed
          to an asynchronous operation, the operation's initiating function returns
          an <code class="computeroutput">awaitable</code> that may be used with the <code class="computeroutput">co_await</code>
          keyword:
        </p>
<pre class="programlisting">std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data), boost::asio::use_awaitable);
</pre>
<p>
          Where an asynchronous operation's handler signature has the form:
        </p>
<pre class="programlisting">void handler(boost::system::error_code ec, result_type result);
</pre>
<p>
          the resulting type of the <code class="computeroutput">co_await</code> expression is <code class="computeroutput">result_type</code>.
          In the <code class="computeroutput">async_read_some</code> example above, this is <code class="computeroutput">size_t</code>.
          If the asynchronous operation fails, the <code class="computeroutput">error_code</code> is converted
          into a <code class="computeroutput">system_error</code> exception and thrown.
        </p>
<p>
          Where a handler signature has the form:
        </p>
<pre class="programlisting">void handler(boost::system::error_code ec);
</pre>
<p>
          the <code class="computeroutput">co_await</code> expression produces a <code class="computeroutput">void</code> result.
          As above, an error is passed back to the coroutine as a <code class="computeroutput">system_error</code>
          exception.
        </p>
<h6>
<a name="boost_asio.overview.core.cpp20_coroutines.h0"></a>
          <span class="phrase"><a name="boost_asio.overview.core.cpp20_coroutines.error_handling"></a></span><a class="link" href="cpp20_coroutines.html#boost_asio.overview.core.cpp20_coroutines.error_handling">Error
          Handling</a>
        </h6>
<p>
          To perform explicit error handling, rather than the default exception-throwing
          behaviour, use the <a class="link" href="../../reference/experimental__as_tuple.html" title="experimental::as_tuple"><code class="computeroutput">experimental::as_tuple</code></a>
          or <a class="link" href="../../reference/redirect_error.html" title="redirect_error"><code class="computeroutput">redirect_error</code></a>
          completion token adapters.
        </p>
<p>
          The <code class="computeroutput">experimental::as_tuple</code> completion token adapter packages
          the completion handler arguments into a single tuple, which is then returned
          as the result of the awaited operation. For example:
        </p>
<pre class="programlisting">boost::asio::awaitable&lt;void&gt; echo(tcp::socket socket)
{
  char data[1024];
  for (;;)
  {
    std::tuple&lt;boost::system::error_code, std::size_t&gt; result =
      co_await socket.async_read_some(boost::asio::buffer(data),
        boost::asio::experimental::as_tuple(boost::asio::use_awaitable));
    if (!std::get&lt;0&gt;(result))
    {
      // success
    }

    // ...
  }
}
</pre>
<p>
          The result can also be captured directly into a structured binding:
        </p>
<pre class="programlisting">boost::asio::awaitable&lt;void&gt; echo(tcp::socket socket)
{
  char data[1024];
  for (;;)
  {
    auto [ec, n] = co_await socket.async_read_some(boost::asio::buffer(data),
        boost::asio::experimental::as_tuple(boost::asio::use_awaitable));
    if (!ec)
    {
      // success
    }

    // ...
  }
}
</pre>
<p>
          Alternatively, the <code class="computeroutput">redirect_error</code> completion token adapter
          may be used to capture the error into a supplied <code class="computeroutput">error_code</code>
          variable:
        </p>
<pre class="programlisting">boost::asio::awaitable&lt;void&gt; echo(tcp::socket socket)
{
  char data[1024];
  for (;;)
  {
    boost::system::error_code ec;
    std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data),
        boost::asio::redirect_error(boost::asio::use_awaitable, ec));
    if (!ec)
    {
      // success
    }

    // ...
  }
}
</pre>
<h6>
<a name="boost_asio.overview.core.cpp20_coroutines.h1"></a>
          <span class="phrase"><a name="boost_asio.overview.core.cpp20_coroutines.coroutines_and_per_operation_cancellation"></a></span><a class="link" href="cpp20_coroutines.html#boost_asio.overview.core.cpp20_coroutines.coroutines_and_per_operation_cancellation">Coroutines
          and Per-Operation Cancellation</a>
        </h6>
<p>
          All threads of execution created by <code class="computeroutput">co_spawn</code> have a cancellation
          state that records the current state of any cancellation requests made
          to the coroutine. To access this state, use <a class="link" href="../../reference/this_coro__cancellation_state.html" title="this_coro::cancellation_state"><code class="computeroutput">this_coro::cancellation_state</code></a>
          as follows:
        </p>
<pre class="programlisting">boost::asio::awaitable&lt;void&gt; my_coroutine()
{
  boost::asio::cancellation_state cs
    = co_await boost::asio::this_coro::cancellation_state;

  // ...

  if (cs.cancelled() != boost::asio::cancellation_type::none)
    // ...
}
</pre>
<p>
          When first created by <code class="computeroutput">co_spawn</code>, the thread of execution has
          a cancellation state that supports <code class="computeroutput">cancellation_type::terminal</code>
          values only. To change the cancellation state, call <a class="link" href="../../reference/this_coro__reset_cancellation_state.html" title="this_coro::reset_cancellation_state"><code class="computeroutput">this_coro::reset_cancellation_state</code></a>.
        </p>
<p>
          By default, continued execution of a cancelled coroutine will trigger an
          exception from any subsequent <code class="computeroutput">co_await</code> of an <code class="computeroutput">awaitable&lt;&gt;</code>
          object. This behaviour can be changed by using <a class="link" href="../../reference/this_coro__throw_if_cancelled.html" title="this_coro::throw_if_cancelled"><code class="computeroutput">this_coro::throw_if_cancelled</code></a>.
        </p>
<h6>
<a name="boost_asio.overview.core.cpp20_coroutines.h2"></a>
          <span class="phrase"><a name="boost_asio.overview.core.cpp20_coroutines.co_ordinating_parallel_coroutines"></a></span><a class="link" href="cpp20_coroutines.html#boost_asio.overview.core.cpp20_coroutines.co_ordinating_parallel_coroutines">Co-ordinating
          Parallel Coroutines</a>
        </h6>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../doc/src/images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
            This is an experimental feature.
          </p></td></tr>
</table></div>
<p>
          The logical operators <code class="computeroutput">||</code> and <code class="computeroutput">&amp;&amp;</code> have
          been overloaded for <code class="computeroutput">awaitable&lt;&gt;</code>, to allow coroutines
          to be trivially awaited in parallel.
        </p>
<p>
          When awaited using <code class="computeroutput">&amp;&amp;</code>, the <code class="computeroutput">co_await</code> expression
          waits until both operations have completed successfully. As a "short-circuit"
          evaluation, if one operation fails with an exception, the other is immediately
          cancelled. For example:
        </p>
<pre class="programlisting">std::tuple&lt;std::size_t, std::size_t&gt; results =
  co_await (
    async_read(socket, input_buffer, use_awaitable)
      &amp;&amp; async_write(socket, output_buffer, use_awaitable)
  );
</pre>
<p>
          Following completion of a <code class="computeroutput">&amp;&amp;</code> operation, the results
          of all operations are concatenated into a tuple. In the above example,
          the first <code class="computeroutput">size_t</code> represents the non-exceptional component
          of the <code class="computeroutput">async_read</code> result, and the second <code class="computeroutput">size_t</code>
          is the result of the <code class="computeroutput">async_write</code>.
        </p>
<p>
          When awaited using <code class="computeroutput">||</code>, the <code class="computeroutput">co_await</code> expression
          waits until either operation succeeds. As a "short-circuit" evaluation,
          if one operation succeeds without throwing an exception, the other is immediately
          cancelled. For example:
        </p>
<pre class="programlisting">std::variant&lt;std::size_t, std::monostate&gt; results =
  co_await (
    async_read(socket, input_buffer, use_awaitable)
      || timer.async_wait(use_awaitable)
  );
</pre>
<p>
          Following completion of a <code class="computeroutput">||</code> operation, the result of the
          first operation to complete non-exceptionally is placed into a <code class="computeroutput">std::variant</code>.
          The active index of the variant reflects which of the operations completed
          first. In the above example, index <code class="computeroutput">0</code> corresponds to the <code class="computeroutput">async_read</code>
          operation.
        </p>
<p>
          These operators may be enabled by adding the <code class="computeroutput">#include</code>:
        </p>
<pre class="programlisting">#include &lt;boost/asio/experimental/awaitable_operators.hpp&gt;
</pre>
<p>
          and then bringing the contents of the <code class="computeroutput">experimental::awaitable_operators</code>
          namespace into scope:
        </p>
<pre class="programlisting">using namespace boost::asio::experimental::awaitable_operators;
</pre>
<h6>
<a name="boost_asio.overview.core.cpp20_coroutines.h3"></a>
          <span class="phrase"><a name="boost_asio.overview.core.cpp20_coroutines.see_also"></a></span><a class="link" href="cpp20_coroutines.html#boost_asio.overview.core.cpp20_coroutines.see_also">See Also</a>
        </h6>
<p>
          <a class="link" href="../../reference/co_spawn.html" title="co_spawn">co_spawn</a>, <a class="link" href="../../reference/detached.html" title="detached">detached</a>,
          <a class="link" href="../../reference/redirect_error.html" title="redirect_error">redirect_error</a>,
          <a class="link" href="../../reference/awaitable.html" title="awaitable">awaitable</a>, <a class="link" href="../../reference/use_awaitable_t.html" title="use_awaitable_t">use_awaitable_t</a>,
          <a class="link" href="../../reference/use_awaitable.html" title="use_awaitable">use_awaitable</a>,
          <a class="link" href="../../reference/this_coro__executor.html" title="this_coro::executor">this_coro::executor</a>,
          <a class="link" href="../../reference/experimental__coro.html" title="experimental::coro">experimental::coro</a>,
          <a class="link" href="../../examples/cpp17_examples.html#boost_asio.examples.cpp17_examples.coroutines_ts_support">Coroutines
          examples</a>, <a class="link" href="coro.html" title="Resumable C++ 20 Coroutines">Resumable
          C++20 Coroutines</a>, <a class="link" href="spawn.html" title="Stackful Coroutines">Stackful
          Coroutines</a>, <a class="link" href="coroutine.html" title="Stackless Coroutines">Stackless
          Coroutines</a>.
        </p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2021 Christopher
      M. Kohlhoff<p>
        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
      </p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="spawn.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../core.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="coro.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
